import datetime
import logging
import random
import string
import sys
from tornado.ioloop import IOLoop
from coin.base.config import Config
from coin.flow.simple_queue import SimpleQueue
from coin.exchange.bitfinex_v2.kr_rest.product import (BitfinexCurrency, BitfinexProduct)
from coin.exchange.bitfinex_v2.order_gateway_margin import BitfinexV2OrderGatewayMargin
from coin.exchange.base.order_gateway import (Order,
                                              OrderSide,
                                              OrderType,
                                              OrderGatewayStatus,
                                              OrderGatewayBase)


def print_working_order(ioloop, og):
  if og.get_working_order():
    print('Working orders:')
    for order in og.get_working_order():
      print('  %s' % str(order))
  else:
    print('No working order')
  ioloop.add_timeout(datetime.timedelta(seconds=5), print_working_order, ioloop, og)


def main(argv):
  ioloop = IOLoop.current()
  currencies = [BitfinexCurrency.FromStr('BTC'), BitfinexCurrency.FromStr('USD')]
  product = BitfinexProduct.FromStr('tBTCUSD')
  products = [product]
  price = 1000.
  qty = 0.004
  order_side = OrderSide.BUY
  order_type = OrderType.LIMIT

  random_str = \
    ''.join(random.choices(string.ascii_lowercase, k=1) +
            random.choices(string.ascii_lowercase + string.digits, k=5))
  queue_name = 'queue-%s%s' % (datetime.datetime.now().strftime('%H%M'), random_str)
  queue = SimpleQueue(queue_name)

  og = BitfinexV2OrderGatewayMargin(currencies, products, Config(filename='bitfinex_inkyu0'))
  og.start(queue, ioloop)
  ioloop.add_timeout(datetime.timedelta(seconds=30), print_working_order, ioloop, og)

  ioloop.add_timeout(datetime.timedelta(seconds=60),
                     og.submit,
                     product,
                     price,
                     qty,
                     order_side,
                     order_type)

  ioloop.add_timeout(datetime.timedelta(seconds=90), og.cancel_all)

  ioloop.start()
  return 0


if __name__ == '__main__':
  logging.basicConfig(level='DEBUG', format='%(levelname)s %(asctime)s %(name)s] %(message)s')
  sys.exit(main(sys.argv))
